import {
	NodeOperationError,
	type INodeType,
	type INodeTypeDescription,
	type IWebhookFunctions,
	type IWebhookResponseData,
} from 'n8n-workflow';
import { checkJWTToken } from './util';
// import { v4 } from 'uuid';

const getResponseCode = (parameters: any) => {
	if (parameters.responseCode) {
		return parameters.responseCode;
	}
	const responseCodeOptions = parameters.options;
	if (responseCodeOptions?.responseCode?.values) {
		const { responseCode, customCode } = responseCodeOptions.responseCode.values;

		if (customCode) {
			return customCode;
		}

		return responseCode;
	}
	return 200;
};

export class ExecNode implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'UNC触发器(慎重使用)',
		name: 'uncTrigger',
		icon: 'file:webhook.svg',
		group: ['trigger'],
		version: 1,
		description: 'UNC触发器(慎重使用)',
		defaults: {
			name: 'UNC Trigger',
		},
		credentials: [
			{
				name: 'JWTNodeApi',
				required: true,
				displayName: 'JWT凭证',
			},
		],
		webhooks: [
			{
				name: 'default',
				httpMethod: 'POST',
				responseMode: '={{$parameter["responseMode"]}}',
				path: '={{$parameter["path"]}}',
				responseCode: `={{(${getResponseCode})($parameter)}}`,
				responseData: '={{$parameter["responseData"]}}',
				isFullPath: true,
			},
		],
		properties: [
			{
				displayName: 'Path',
				name: 'path',
				type: 'string',
				default: '={{$workflow.id}}',
				placeholder: 'webhook',
				required: true,
				description:
					"请输入路径",
			},
			{
				displayName: '响应模式',
				name: 'responseMode',
				type: 'options',
				options: [
					{
						name: '工作流执行完成',
						value: 'lastNode'
					},
					{
						name: "响应节点",
						value: 'responseNode',
					},
				],
				default: 'responseNode'
			},
			{
				displayName: '自定义响应数据',
				name: 'responseData',
				type: 'options',
				displayOptions: {
					show: {
						responseMode: ['lastNode'],
					},
				},
				options: [
					{
						name: '所有数据',
						value: 'allEntries',
						description: '返回最后一个节点所有数据',
					},
					{
						name: '第一条数据',
						value: 'firstEntryJson',
						description:
							'返回最后一个节点第一条数据',
					},
					{
						name: '不返回数据',
						value: 'noData',
					},
				],
				default: 'firstEntryJson',
			},
		],
		inputs: [],
		outputs: ['main']
	};

	async webhook(this: IWebhookFunctions): Promise<IWebhookResponseData> {
		const responseMode = this.getNodeParameter('responseMode', 'responseNode') as string;
		const responseData = responseMode == 'lastNode' ? this.getNodeParameter('responseData', 'firstEntryJson') as string : undefined;
		if (responseMode == 'responseNode') { // 只有响应节点时检查
			const connectedNodes = this.getChildNodes(this.getNode().name);
			const isRespondToWebhookConnected = connectedNodes.some(
				(node) => {
					return node.type === 'n8n-nodes-exec-webhook.uncResponse' || node.type === 'CUSTOM.uncResponse'
				},
			);
			if (!isRespondToWebhookConnected) {
				throw new NodeOperationError(
					this.getNode(),
					new Error('No Respond to Webhook node found in the workflow'),
					{
						description:
							'Insert a Respond to Webhook node to your workflow to respond to the webhook or choose another option for the “Respond” parameter',
					},
				);
			}
		}
		const resp = this.getResponseObject();
		try {
			const credentials: any = await this.getCredentials('JWTNodeApi');
			const headers = this.getHeaderData();
			checkJWTToken({
				secretKey: credentials?.keypass,
				token: headers?.authorization,
			});
		} catch (error) {
			// 必须成对出现
			resp.writeHead(403, { 'WWW-Authenticate': 'Basic realm="Webhook"' });
			resp.end(error?.message);
			return { noWebhookResponse: true };
		}
		return {
			webhookResponse: responseData,
			workflowData: [
				this.helpers.returnJsonArray(this.getBodyData()),
			],
		};
	}

}
